/*
 * PopupUsersWidget.cpp
 *
 *  Created on: Jul 9, 2012
 *      Author: guillou
 */

#include <PopupUsersWidget.hpp>
#include <PopupGuiCore.hpp>
#include <PopupUtilities.hpp>
#include <PopupUserProfileFrame.hpp>

using namespace Popup;

PopupUsersWidget::PopupUsersWidget(QWidget *parent,
                                   const UserList & p_filterOut)
: QWidget(parent), m_parent(parent),
  m_filterOut(p_filterOut), m_userProfileFrame(0)
{
  setupUi(this);
  m_usersTable->setModel(&m_usersTableModel);
  m_usersTable->setColumnHidden(0, true);
  m_usersTable->setContextMenuPolicy(Qt::CustomContextMenu);

  QHeaderView *_headerView = m_usersTable->horizontalHeader();
  _headerView->setResizeMode(QHeaderView::Stretch);
  _headerView->setMinimumSectionSize(30);
  _headerView->setDefaultSectionSize(30);
  _headerView->setResizeMode(1, QHeaderView::Stretch);
  _headerView->setResizeMode(2, QHeaderView::ResizeToContents);
  _headerView->setResizeMode(3, QHeaderView::ResizeToContents);
  _headerView->setResizeMode(4, QHeaderView::ResizeToContents);
  _headerView->setResizeMode(5, QHeaderView::ResizeToContents);
  _headerView->setResizeMode(6, QHeaderView::ResizeToContents);

  PopupUsersManager::instance()->registerObserver(this);

  m_friendsListsCombo->addItems(PopupSettings::instance()->friendsListsNames());

  connect(m_saveFriendsBtn, SIGNAL(clicked()),
            this, SLOT(slot_saveFriendsList()));
  connect(m_friendsListsCombo->lineEdit(), SIGNAL(returnPressed()),
          this, SLOT(slot_saveFriendsList()));
  connect(m_friendsListsCombo, SIGNAL(currentIndexChanged(QString)),
          this, SLOT(slot_loadFriendsList(QString)));
  connect(m_unselectAllBtn, SIGNAL(clicked()),
          this, SLOT(slot_onUnselectAll()));
  connect(m_usersTable, SIGNAL(customContextMenuRequested(QPoint)),
          this, SLOT(slot_customContextMenuRequested(QPoint)));
}

PopupUsersWidget::~PopupUsersWidget()
{
  PopupUsersManager::instance()->unregisterObserver(this);
}

void PopupUsersWidget::displayStatistics(bool p_show)
{
  m_usersTable->setColumnHidden(3, !p_show);
  m_usersTable->setColumnHidden(4, !p_show);
  m_usersTable->setColumnHidden(5, !p_show);
  m_usersTable->setColumnHidden(6, !p_show);
}

void PopupUsersWidget::userUpdated(const PopupUserExt *p_user,
                                   unsigned short p_updateMask,
                                   bool p_isNewUser)
{
  if (p_user->getID() == getMyID())
  {
    if (!p_user->isAlive()) {
      m_usersTableModel.removeAll();
    }
  }
  else
  {
    bool _ignore = false;

    if (p_isNewUser && m_filterOut.size() > 0) {
      for (UserList::const_iterator _it = m_filterOut.begin();
          _it != m_filterOut.end(); _it++) {
        if (*_it == p_user->getID()) {
          _ignore = true;
          break;
        }
      }
    }

    if (!_ignore) {
      m_usersTableModel.updateUser(p_user, p_updateMask, p_isNewUser);
    }
  }
}

void PopupUsersWidget::userStatisticsUpdated(const PopupUserExt *p_user,
                                             unsigned short p_updateMask)
{
  m_usersTableModel.updateUserStatistics(p_user, p_updateMask);
}

bool PopupUsersWidget::hasSelection() {
  return m_usersTable->selectionModel()->hasSelection();
}

void PopupUsersWidget::getSelectedUsers(UserList & p_users)
{
  QItemSelectionModel *_selectModel = m_usersTable->selectionModel();
  if (_selectModel->hasSelection()) {
    QModelIndexList _selectedItems = _selectModel->selectedRows();
    QModelIndexList::iterator _itSel;
    for (_itSel = _selectedItems.begin(); _itSel != _selectedItems.end(); _itSel++)
    {
      p_users.insert(_itSel->data(PopupGuiCore::POPUP_USER_ID).toUInt());
    }
  }
}

void PopupUsersWidget::slot_loadFriendsList(QString p_name)
{
  UserList _friends;
  QItemSelection _selection;
  QItemSelectionModel *_selectModel = m_usersTable->selectionModel();
  if (PopupSettings::instance()->friendsList(p_name, _friends)) {
    m_usersTableModel.selectUsers(_selection, _friends);
  }
  _selectModel->select(_selection, QItemSelectionModel::ClearAndSelect);
}

void PopupUsersWidget::slot_saveFriendsList()
{
  QString _name = m_friendsListsCombo->currentText();
  if (_name.isEmpty()) {
    utilities::showError("Please set a name for your friends list!", this);
  } else {
    UserList _users;
    getSelectedUsers(_users);
    if (_users.size() < 2) {
      utilities::showError("Please select at least 2 friends "
          "in order to save your list!", this);
    } else {
      PopupSettings::instance()->setFriendsList(_name, _users);
      PopupSettings::instance()->serialize(PopupSettings::POPUP_SAVE_TO_FILE);
      m_friendsListsCombo->insertItem(m_friendsListsCombo->count(), _name);
      m_friendsListsCombo->setCurrentIndex(m_friendsListsCombo->findText(_name));
    }
  }
}

void PopupUsersWidget::slot_onUnselectAll()
{
  m_friendsListsCombo->setCurrentIndex(0);
}

void PopupUsersWidget::slot_customContextMenuRequested(QPoint p_point)
{
  bool _ok;
  QModelIndex _index = m_usersTable->indexAt(p_point);
  QStandardItem *_item = m_usersTableModel.item(_index.row());
  if (_item != 0)
  {
    if (m_userProfileFrame == 0) {
      m_userProfileFrame = new PopupUserProfileFrame();
    }
    if (m_userProfileFrame->setup(
        _item->data(PopupGuiCore::POPUP_USER_ID).toUInt(&_ok))) {
      QPoint _point = mapToGlobal(QPoint(p_point.x() - 15, p_point.y() - 15));
      m_userProfileFrame->move(_point);
      m_userProfileFrame->setVisible(true);
    }
  }
}
